package uk.ac.cam.cl.projectcharlie2010.game.player;

import uk.ac.cam.cl.projectcharlie2010.engines.Engine;
import ch.nostromo.tiffanys.engines.EngineSettings;
import ch.nostromo.tiffanys.game.player.PlayerException;

public class PlayerEngine extends Player {

	private Engine engine;

	private Class<Engine> engineClass = null;

	private EngineSettings engineSettings = null;
	
	private boolean active = true;

	@Override
	public PlayerEngine clone() throws CloneNotSupportedException {
		PlayerEngine result = (PlayerEngine) super.clone();

		result.engineClass = engineClass;
		result.engine = null;
		result.engineSettings = engineSettings.clone();
		result.active = active;

		return result;
	}

	public PlayerEngine(Class<Engine> Class, EngineSettings engineSettings) {
		this.engineClass = Class;
		this.engineSettings = engineSettings;
	}

	public Class<Engine> getEngineClass() {
		return engineClass;
	}

	public EngineSettings getEngineSettings() {
		return engineSettings;
	}

	public Engine getEngineInstance() throws PlayerException {
		//Did they really want this? It's weird that they create a new engine on every call
		try {
			engine = engineClass.newInstance();
			engine.setEngineSettings(engineSettings);
			setActive(active);
			return engine;
		} catch (InstantiationException e) {
			throw new PlayerException("InstantiationException", e);
		} catch (IllegalAccessException e) {
			throw new PlayerException("IllegalAccessException", e);
		}
	}

	@Override
	public String getPlayerName() throws PlayerException {

//		SHIT! This method actually changes what engine is running! Does that ever make sense?
				return getEngineInstance().getEngineName();
	//TODO Maybe use this instead?	
//		if (engine != null) {
//			return engine.getEngineName();
//		} else {
//			return null;
//		}

	}

	public void setEngineSettings(EngineSettings engineSettings) {
		this.engineSettings = engineSettings;
	}

	@Override
	public void setActive(boolean active) {
		this.active = active;
		if (active) {
			System.out.println("Engine Activating");
		} else {
			System.out.println("Engine Deactivating");
		}
		if (engine != null) {
			System.out.println("engine activity change");
			engine.setActive(active);
		} else {
			System.out.println("engine null");
		}
	}

	@Override
	public void kill() {
		if (engine != null) {
			engine.kill();
		}
	}

}
